#pragma once

#include <iostream>
#include <string>
#include <cstdarg>
#include <time.h>
#include <unistd.h>

#define DEBUG (1 << 0)
#define NORMAL (1 << 1)
#define WARNING (1 << 2)
#define ERROR (1 << 3)
#define FATAL (1 << 4)

#define NUM 1024

#define LOG_NORMAL "log.txt"
#define LOG_ERR "log.error"

const char *to_levelstr(int level)
{
    switch (level)
    {
    case DEBUG:
        return "DEBUG";
    case NORMAL:
        return "NORMAL";
    case WARNING:
        return "WARNING";
    case ERROR:
        return "ERROR";
    case FATAL:
        return "FATAL";
    default:
        return nullptr;
    }
}

void logMessage(int level, const char *format, ...)
{
    // [日志等级] [时间戳/时间] [pid] [message]
    // [WARNING] [2025-05-12] [123] [创建socket失败]

    time_t rawtime;
    time(&rawtime);
    struct tm *stm = gmtime(&rawtime);
    std::string time_str = "";
    // 2025-5-17/17:37
    time_str += std::to_string(stm->tm_year + 1900);
    time_str += "-";
    time_str += std::to_string(stm->tm_mon + 1);
    time_str += "-";
    time_str += std::to_string(stm->tm_mday);
    time_str += "/";
    time_str += std::to_string(stm->tm_hour + 8);
    time_str += ":";
    time_str += std::to_string(stm->tm_min);
    time_str += ":";
    time_str += std::to_string(stm->tm_sec);

    char logprefix[NUM];
    snprintf(logprefix, sizeof(logprefix), "[%s][%s][pid: %d]",
             to_levelstr(level), time_str.c_str(), getpid());

    char logcontent[NUM];
    va_list arg;
    va_start(arg, format);
    vsnprintf(logcontent, sizeof(logcontent), format, arg);

    std::cout << logprefix << logcontent << std::endl;

    // FILE *log = fopen(LOG_NORMAL, "a");
    // FILE *err = fopen(LOG_ERR, "a");
    // if (log != nullptr && err != nullptr)
    // {
    //     if (level & (DEBUG | NORMAL | WARNING))
    //         fprintf(log, "%s%s\n", logprefix, logcontent);
    //     if (level & (ERROR | FATAL))
    //         fprintf(err, "%s%s\n", logprefix, logcontent);
    // }
    // fclose(log);
    // fclose(err);
}